package hu.magyusz.mailhide.util;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MailHideUtils {

    public static byte[] toBinArray(String hexStr) {
        byte bArray[] = new byte[hexStr.length() / 2];
        for (int i = 0; i < (hexStr.length() / 2); i++) {
            byte firstNibble = Byte.parseByte(hexStr.substring(2 * i, 2 * i + 1), 16); // [x,y)
            byte secondNibble = Byte.parseByte(hexStr.substring(2 * i + 1, 2 * i + 2), 16);
            int finalByte = (secondNibble) | (firstNibble << 4); // bit-operations only with numbers, not bytes.
            bArray[i] = (byte) finalByte;
        }
        return bArray;
    }
    
    public static String pad(String in, int block_size){
        String ret = in;
        int numpad = block_size - (in.length() % block_size);
        for (int i = 1; i <=numpad; i++) {
           ret+= (char)numpad;
       }
        return ret;
    }
    
    private static byte[] iv = new byte[] {
            (byte)0, (byte)0, (byte)0, (byte)0,
            (byte)0, (byte)0, (byte)0, (byte)0,
            (byte)0, (byte)0, (byte)0, (byte)0,
            (byte)0, (byte)0, (byte)0, (byte)0};

    public static String getUrl(String privKey, String pubKey, String email) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(MailHideUtils.toBinArray(privKey), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey,  new IvParameterSpec (iv));
            byte[] encrypted = cipher.doFinal(pad(email,16).getBytes());
            String encoded = Base64.encodeBytes(encrypted, Base64.URL_SAFE);
            return "http://mailhide.recaptcha.net/d?k="+pubKey+"&c="+encoded;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error";
    }

}
